package com.yssoft.controller.app.production;

import com.yssoft.entity.production.TPackageCode;
import com.yssoft.service.production.ProductionProcessService;
import com.yssoft.utils.AppUtil;
import org.apache.commons.codec.DecoderException;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @创建人 陈翼东
 * @说明 生产过程controller
 * @时间 2018/5/9 上午 11:00
 */
@CrossOrigin
@RestController
@RequestMapping("/app/productionProcess")
public class ProductionProcessController {

    private static Logger logger = Logger.getLogger(ProductionProcessController.class);

    @Resource
    private ProductionProcessService productionProcessService;

    /**
     * @方法名: getTechnologyInfo
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:22
     * @参数: [productId] 成品id
     * @返回值: java.lang.Object
     * @说明: 获取加工工艺信息
     */
    @RequestMapping(value = "/getTechnologyInfo", method = RequestMethod.POST)
    public Object getTechnologyInfo(String productId, Integer workId, HttpServletRequest request) {
        if (productId == null && productId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递成品id", null);
        } else {
            try {
                List<Map<String, Object>> technologyList = productionProcessService.findTechnologyByProduct(Integer.parseInt(productId), request);
                for (Map<String, Object> stringObjectMap : technologyList) {
                    List<Map<String, Object>> index = productionProcessService.findIndexAndValueByProcessingTechnic(stringObjectMap.get("id") + "", workId);
                    // 按照code从小到大排序（使用匿名内部类以兼容旧版本Java）
                    Collections.sort(index, new Comparator<Map<String, Object>>() {
                        @Override
                        public int compare(Map<String, Object> a, Map<String, Object> b) {
                            String codeA = a.get("code") != null ? a.get("code").toString() : "";
                            String codeB = b.get("code") != null ? b.get("code").toString() : "";
                            return codeA.compareTo(codeB);
                        }
                    });
                    stringObjectMap.put("technicIndex", index);
                }
                return AppUtil.returnListJson("1", "查询成功", technologyList);
            } catch (Exception e) {
                logger.error(e.getMessage());
                return AppUtil.returnMapJson("0", "查询失败", null);
            }
        }
    }

    /**
     * @方法名: getTechnologyIndexAndValue
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:21
     * @参数: [technologyId] 工艺id
     * @返回值: java.lang.Object
     * @说明: 查询工艺对应的指标信息和值, 需要传工单ID
     */
    @RequestMapping(value = "/getTechnologyIndexAndValue", method = RequestMethod.POST)
    public Object getTechnologyIndexAndValue(String technologyId, Integer workId) {
        if (technologyId == null && technologyId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递加工工艺实体id", null);
        }
        try {
            List<Map<String, Object>> technologyList = productionProcessService.findIndexAndValueByProcessingTechnic(technologyId, workId);
            // 按照code从小到大排序
            Collections.sort(technologyList, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> a, Map<String, Object> b) {
                    String codeA = a.get("code") != null ? a.get("code").toString() : "";
                    String codeB = b.get("code") != null ? b.get("code").toString() : "";
                    return codeA.compareTo(codeB);
                }
            });
            return AppUtil.returnListJson("1", "查询成功", technologyList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AppUtil.returnMapJson("0", "查询失败", null);
        }
    }

    /**
     * @方法名: getTechnologyIndicators
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:21
     * @参数: [technologyId] 工艺id
     * @返回值: java.lang.Object
     * @说明: 查询工艺对应的指标信息
     */
    @RequestMapping(value = "/getTechnologyIndex", method = RequestMethod.POST)
    public Object getTechnologyIndex(String technologyId) {
        if (technologyId == null && technologyId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递加工工艺实体id", null);
        }
        try {
            List<Map<String, Object>> technologyList = productionProcessService.findIndexByProcessingTechnic(technologyId);
            return AppUtil.returnListJson("1", "查询成功", technologyList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AppUtil.returnMapJson("0", "查询失败", null);
        }
    }

    /**
     * @方法名: saveTechnologyIndicators
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:52
     * @参数: indicatorIds 工艺指标id
     * @参数: tWorksheeId 加工单id
     * @返回值: java.lang.Object
     * @说明: 保存工艺指标采集的数据(正常文本值和附件值都用gValue来接受根据加工工艺中的指标类型判断保存时候是否有附件, 指标值使用工艺指标id + Value来接收)
     */
    @RequestMapping(value = "saveTechnologyIndicators", method = RequestMethod.POST)
    public Object saveTechnologyIndicators(String[] indicatorIds, String tWorksheeId, HttpServletRequest request) throws IOException, DecoderException {
        return productionProcessService.addTechnologyIndicators(indicatorIds, tWorksheeId, request);
    }

    /**
     * @方法名: saveTechnologyIndicators
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:52
     * @参数: indicatorIds 工艺指标id
     * @参数: tWorksheeId 加工单id
     * @返回值: java.lang.Object
     * @说明: 修改工艺指标采集的数据(正常文本值和附件值都用gValue来接受根据加工工艺中的指标类型判断保存时候是否有附件, 指标值使用工艺指标id + Value来接收)
     */
    @RequestMapping(value = "updateTechnologyIndicators", method = RequestMethod.POST)
    public Object updateTechnologyIndicators(String[] indicatorIds, String tWorksheeId, HttpServletRequest request) {
        try {
            if (request.getHeader("content-type") != null && "application/x-www-form-urlencoded".equals(request.getHeader("content-type"))) {
                return null;//不支持断点续传，直接返回null即可
            }
            productionProcessService.editTechnologyIndicators(indicatorIds, tWorksheeId, request);
            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (IOException e) {
            return AppUtil.returnMapJson("0", "保存失败!", null);
        } catch (DecoderException e) {
            return AppUtil.returnMapJson("0", "保存失败!", null);
        } catch (ParseException e) {
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }
    }


    /**
     * @方法名: getWorksheetAndProducts
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 03:37
     * @参数: worksheetId 加工单id
     * @返回值: java.lang.Object
     * @说明: 获取加工单信息和成品加工类型, 批次码
     */
    @RequestMapping(value = "getWorksheetAndProducts", method = RequestMethod.POST)
    public Object getWorksheetAndProducts(String worksheetId) {
        try {
            List<Map<String, Object>> worksheetAndProducts = productionProcessService.findWorksheetAndProducts(worksheetId);
            return AppUtil.returnListJson("1", "查询成功!", worksheetAndProducts);
        } catch (Exception e) {
            logger.error("查询加工单信息和成品加工类型,批次码失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "查询失败!", null);
        }
    }

    /**
     * @方法名: getBatchAndProducts
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 04:25
     * @参数: [code] 标签码
     * @返回值: java.lang.Object
     * @说明: 获取标签码对应的批次信息, 溯源类型信息
     */
    @RequestMapping(value = "getBatchAndProducts", method = RequestMethod.POST)
    public Object getBatchAndProducts(String code) {
        try {
            Map<String, Object> result = productionProcessService.findBatchAndSourceType(code);
            return AppUtil.returnMapJson("1", "查询成功!", result);
        } catch (Exception e) {
            logger.error("查询标签对应的批次码和溯源类型失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "查询失败!", null);
        }
    }

    /**
     * @方法名: getScanHistory
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 04:48
     * @参数: [packageCode] 包装码
     * @返回值: java.lang.Object
     * @说明: 获取包装码已经扫过的标签码
     */
    @RequestMapping(value = "getScanHistory", method = RequestMethod.POST)
    public Object getScanHistory(String packageCode) {
        try {
            List<Map<String, Object>> result = productionProcessService.findHistoryLableByPackageCode(packageCode);
            return AppUtil.returnListJson("1", "查询成功!", result);
        } catch (Exception e) {
            logger.error("查询包装码已经扫过的标签码" + e.getMessage());
            return AppUtil.returnListJson("0", "查询失败!", null);
        }
    }

    /**
     * @方法名: getPackageNum
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 05:25
     * @参数: [packageCode, worksheetId]
     * @返回值: java.lang.Object
     * @说明: 根据扫描的包装码获取包装的数量(数量在成品或者半成品表与物料的中间表中)
     */
    @RequestMapping(value = "getPackageNum", method = RequestMethod.POST)
    public Object getPackageNum(String packageCode, String worksheetId) {
        try {
            Map<String, Object> number = productionProcessService.getPackageNumber(packageCode, worksheetId);
            return AppUtil.returnMapJson("1", "获取成功!", number);
        } catch (Exception e) {
            return AppUtil.returnMapJson("0", "获取失败!", null);
        }
    }


    /**
     * @方法名: getPackageNum
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 05:25
     * @参数: [packageCode, worksheetId]
     * @返回值: java.lang.Object
     * @说明: 根据扫描的包装码获取加工单
     */
    @RequestMapping(value = "getWorksheetByPackage", method = RequestMethod.POST)
    public Object getWorksheetByPackage(String packageCode) {
        try {
            Map<String, Object> number = productionProcessService.getworksheetByPackage(packageCode);
            return AppUtil.returnMapJson("1", "获取成功!", number);
        } catch (Exception e) {
            e.printStackTrace();
            return AppUtil.returnMapJson("0", "获取失败!", null);
        }
    }

    /**
     * @方法名: saveSemiFinishedProductsNum
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 04:59
     * @参数: [num, worksheetId]实际加工半成品的数量, 加工单id
     * @返回值: java.lang.Object
     * @说明: 半成品的加工单实际生产数量保存
     */
    @RequestMapping(value = "saveSemiFinishedProductsNum", method = RequestMethod.POST)
    public Object saveSemiFinishedProductsNum(String num, String worksheetId) {
        return productionProcessService.saveSemiFinishedProductNum(num, worksheetId);
    }

    /**
     * @方法名: saveBatchScan
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 05:13
     * @参数: [lableCode, batchNum, worksheetId] 标签码,加工数量,加工单id
     * @返回值: java.lang.Object
     * @说明: 批次溯源类型的商品扫码之后保存
     */
    @RequestMapping(value = "saveBatchScan", method = RequestMethod.POST)
    public Object saveBatchScan(String lableCode, String batchNum, String worksheetId, HttpServletRequest request) {
        try {
            return productionProcessService.saveBatchScan(lableCode, batchNum, worksheetId, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("按批次溯源商品扫码保存失败" + e.getMessage());
            return AppUtil.returnMapJson("1", "保存失败!", null);
        }
    }

    /**
     * @方法名: saveUnitNoPackage
     * @创建人: 陈翼东
     * @时间: 2018/5/10 上午 08:39
     * @参数: [lableCode, worksheetId] 标签码,加工单id
     * @返回值: java.lang.Object
     * @说明: 个体溯源无包装码方式扫码保存
     */
    @RequestMapping(value = "saveUnitNoPackage", method = RequestMethod.POST)
    public Object saveUnitNoPackage(String[] lableCode, String worksheetId, HttpServletRequest request) {
        try {
            return productionProcessService.saveUnitNoPackage(lableCode, worksheetId, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("个体溯源无包装码扫码保存失败" + e.getMessage());
            return AppUtil.returnMapJson("1", "保存失败!", null);
        }
    }

    /**
     * @方法名: saveUnitIsPackage
     * @创建人: 陈翼东
     * @时间: 2018/5/10 上午 08:43
     * @参数: [packageCode, lableCode, worksheetId] 包装码 ,标签码,加工单id
     * @返回值: java.lang.Object
     * @说明: 个体溯源有包装码方式扫码保存
     */
    @RequestMapping(value = "saveUnitIsPackage", method = RequestMethod.POST)
    public Object saveUnitIsPackage(String packageCode, String[] lableCode, String worksheetId, HttpServletRequest request) {
        try {
            return productionProcessService.saveUnitIsPackage(packageCode, lableCode, worksheetId, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("个体溯源有包装码扫码保存失败" + e.getMessage());
            return AppUtil.returnMapJson("1", "保存失败!", null);
        }
    }

    /**
     * 获取加工单扫描历史(历史使用包装码来存储，包装码中有扫描时间和扫描人的说明加工单已经扫描过了)
     *
     * @return
     */
    @RequestMapping(value = "getWorksheetScanHistory", method = RequestMethod.POST)
    public Object getWorksheetScanHistory(String worksheetId) {
        List<Map<String, Object>> result = productionProcessService.getWorksheetScanHistory(worksheetId);
        return AppUtil.returnListJson("1", "获取成功!", result);
    }

    /**
     * @方法名: packageIsWorksheet
     * @创建人: 陈翼东
     * @时间: 2018/5/12 下午 03:37
     * @参数: [packageCode]
     * @返回值: java.lang.Object
     * @说明: 1.5.    查询包装码时是否是当前加工单，是否被扫描过
     */
    @RequestMapping(value = "packageIsWorksheet", method = RequestMethod.POST)
    public Object packageIsWorksheet(String packageCode) {
        try {
            TPackageCode result = productionProcessService.getPackageByCode(packageCode);
            return AppUtil.returnObjectJson("1", "获取成功!", result);
        } catch (Exception e) {
            return AppUtil.returnMapJson("0", "获取失败!", null);
        }
    }

    @RequestMapping(value = "deleteFile", method = RequestMethod.POST)
    public Object deleteFile(String fileKey) {
        try {
            int fileUrlIndex = fileKey.indexOf("/files");
            String newFileUrl = fileKey.substring(fileUrlIndex);
            productionProcessService.deleteFileByUrl(newFileUrl);
            return AppUtil.returnMapJson("1", "删除成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return AppUtil.returnMapJson("0", "删除失败", null);
        }

    }

}
